﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using AjaxControlToolkit;

public partial class Admin_AddArticle : System.Web.UI.Page
{
    DataTable dtTags;
    Int32 iArticleID;
    NewsType pageType;

    protected void Page_Load(object sender, EventArgs e)
    {
        GetParameters();
        if (pageType == NewsType.deadSea || pageType==NewsType.aboutUS)
        {
            switch (pageType)
            {
                case NewsType.deadSea:
                    lblTitle.InnerText="Лечение на мертвом море";
                    break;
                case NewsType.aboutUS:
                    lblTitle.InnerText="О нас";
                    break;
            }
            pnlNews.Visible = false;
            SetPageType();
            //iArticleID = (int)Articles.GetArticleCatID((int)pageType).articleId;
            GetArticleToEditbyType((int)pageType);
        }
        else if (pageType == NewsType.Wiki)
        {
            SetPageType();
        }
        else
        {
            if (!IsPostBack)
            {
                ViewState["pnlAddArticleVisible"] = false;
                pnlAddArticle.Style.Add("display", "none");
            }
        }
        if (iArticleID == 0)
            InitData();
        else
        {
            if (pageType != NewsType.aboutUS && pageType != NewsType.deadSea)
            {
                GetArticleToEdit();
                SetPageType();
            }
            btnToImages.Visible = true;
        }
        this.Page.ClientScript.RegisterOnSubmitStatement(
    this.GetType(),
    "AjaxHack",
    "for ( var i = 0; i < parent.frames.length; ++i ) if ( parent.frames[i].FCK ) parent.frames[i].FCK.UpdateLinkedField();"
    );

        if (dtTags == null)
            if (ViewState["tags"] != null)
                dtTags = (DataTable)ViewState["tags"];
            else
            {
                dtTags = new DataTable();
                dtTags.Columns.Add("KeyID");
                dtTags.Columns.Add("KeyName");
            }
    }

    private void GetParameters()
    {
        iArticleID =Convert.ToInt32(Request.QueryString["ID"]);
        pageType = (NewsType)Convert.ToInt32(Request.QueryString["type"]);
        if (pageType > 0)
            ViewState["pageType"] = pageType;
        else
            pageType =(ViewState["pageType"]!=null)?(NewsType)ViewState["pageType"]:0;
    }

    private void InitData()
    {
        if (!IsPostBack)
        {
            try
            {
                ViewState["tags"] = null;
                ddlCategories.DataSource = Dal.ExecuteDBsp("Admin_GetRootCategories");
                ddlCategories.DataBind();

                ddlCategories.Items.Insert(0, new ListItem("Выберите раздел", "-1", true));


                // Load tags
                cmbTags.DataSource = Dal.ExecuteDBsp("usp_KeyWordsGet");
                cmbTags.DataBind();
            }
            catch { }
        }
        else
        {
            if (ddlCategories.Items.Contains(new ListItem("Выберите раздел", "-1")))
                ddlCategories.Items.Remove(new ListItem("Выберите раздел", "-1"));
        }
    }

    private void GetArticleToEdit()
    {
        if (!IsPostBack)
        {
            ViewState["pnlAddArticleVisible"] = true;
            pnlAddArticle.Style.Clear();

            ddlCategories.DataSource = Dal.ExecuteDBsp("Admin_GetRootCategories");
            ddlCategories.DataBind();

            // Load tags
            cmbTags.DataSource = Dal.ExecuteDBsp("usp_KeyWordsGet");
            cmbTags.DataBind();

            Dal.arParams.Clear();
            Dal.arParams.Add(iArticleID);
            DataSet dsArticle = Dal.ExecuteDBspDS("usp_GetArticleByID", Dal.arParams);

            if (dsArticle.Tables[0].Rows.Count > 0)
            {
                DataRow dr = dsArticle.Tables[0].Rows[0];
                txtBrowserTitle.Text = dr["browserTitle"].ToString();
                txtTitle.Text = dr["Title"].ToString();
                txtUrl.Text = dr["cPageName"].ToString();
                txtSubTitle.Value = dr["SubTitle"].ToString();
                DateTime publishDate = DateTime.Parse(dr["PublishDate"].ToString());
                txtPublishDate.Text = publishDate.ToShortDateString();
                txtPublishTime.Text = publishDate.ToShortTimeString();
                edArticle.Value = dr["Article"].ToString();
                chkShowArticle.Checked = Convert.ToBoolean(Convert.ToInt16(dr["isVisible"]));
                chkShowDateDime.Checked = Convert.ToBoolean(Convert.ToInt16(dr["isDateVisible"]));
                try
                {
                    int iCatID = Convert.ToInt32(dr["CatID"]);
                    ArrayList arrCats = new ArrayList(3);
                    while (iCatID != -1)
                    {
                        arrCats.Add(iCatID);
                        Dal.arParams.Clear();
                        Dal.arParams.Add(iCatID);
                        iCatID = Convert.ToInt32(Dal.ExecuteDBsp("usp_GetCategoryById", Dal.arParams).Rows[0]["ancestor"]);
                    }

                    ddlCategories.SelectedValue = arrCats[arrCats.Count-1].ToString();
                    pageType = (NewsType)arrCats[arrCats.Count - 1];
                    ViewState["pageType"] = pageType;
                    
                        SetPageType();
                    
                    switch (pageType)
                    {
                        case NewsType.MedicalCenters:
                            ddlMedCenters.SelectedValue = arrCats[arrCats.Count - 2].ToString();
                            break;
                        case NewsType.hotels:
                            ddlMedCenters.SelectedValue = arrCats[arrCats.Count - 2].ToString();
                            break;
                        case NewsType.Wiki:
                            ddlWiki.SelectedValue = arrCats[arrCats.Count - 2].ToString();
                            ddlWiki_SelectedIndexChanged(this, new EventArgs());
                            ddlWikiSubCat.SelectedValue = arrCats[arrCats.Count - 3].ToString();
                            break;
                    }
                }
                catch
                {
                    ddlCategories.SelectedValue = "0";
                }
            }
            txtPageKeywords.Text=PageHeaderData.GetArticleKeywords(iArticleID);
            if (dsArticle.Tables.Count > 1)
            {
                if (dsArticle.Tables[1].Rows.Count > 0)
                {
                    dtTags = dsArticle.Tables[1];
                    ViewState["tags"] = dtTags;

                    rptTags.DataSource = dtTags;
                    rptTags.DataBind();
                }
            }
        }
    }

    private void GetArticleToEditbyType(int iType)
    {

        if (!IsPostBack)
        {// Load tags
            cmbTags.DataSource = Dal.ExecuteDBsp("usp_KeyWordsGet");
            cmbTags.DataBind();

            Dal.arParams.Clear();
            Dal.arParams.Add(iType);
            DataSet dsArticle = Dal.ExecuteDBspDS("usp_GetArticleByCatID", Dal.arParams);

            if (dsArticle.Tables[0].Rows.Count > 0)
            {
                DataRow dr = dsArticle.Tables[0].Rows[0];
                iArticleID = Convert.ToInt32(dr["articleID"]);
                ViewState["iArticleID"] = iArticleID;
                txtBrowserTitle.Text = dr["browserTitle"].ToString();
                txtTitle.Text = dr["Title"].ToString();
                txtUrl.Text = dr["cPageName"].ToString();
                txtUrl.ReadOnly = true;
                txtSubTitle.Value = dr["SubTitle"].ToString();
                DateTime publishDate = DateTime.Parse(dr["PublishDate"].ToString());
                txtPublishDate.Text = publishDate.ToShortDateString();
                txtPublishTime.Text = publishDate.ToShortTimeString();
                edArticle.Value = dr["Article"].ToString();
                chkShowArticle.Checked = Convert.ToBoolean(Convert.ToInt16(dr["isVisible"]));
                chkShowDateDime.Checked = Convert.ToBoolean(Convert.ToInt16(dr["isDateVisible"]));

                try
                {
                    int iCatID = Convert.ToInt32(dr["CatID"]);
                    ArrayList arrCats = new ArrayList(3);
                    while (iCatID != -1)
                    {
                        arrCats.Add(iCatID);
                        Dal.arParams.Clear();
                        Dal.arParams.Add(iCatID);
                        iCatID = Convert.ToInt32(Dal.ExecuteDBsp("usp_GetCategoryById", Dal.arParams).Rows[0]["ancestor"]);
                    }

                    ddlCategories.SelectedValue = arrCats[arrCats.Count - 1].ToString();
                    pageType = (NewsType)arrCats[arrCats.Count - 1];
                    ViewState["pageType"] = pageType;
                    switch (pageType)
                    {
                        case NewsType.MedicalCenters:
                            ddlMedCenters.SelectedValue = arrCats[arrCats.Count - 2].ToString();
                            break;
                        case NewsType.deadSea:
                            ddlCategories.SelectedValue = "0";
                            break;
                    }
                }
                catch
                {
                    ddlCategories.SelectedValue = "0";
                }
            }
            txtPageKeywords.Text = PageHeaderData.GetArticleKeywords(iArticleID);
            if (dsArticle.Tables.Count > 1)
            {
                if (dsArticle.Tables[1].Rows.Count > 0)
                {
                    dtTags = dsArticle.Tables[1];
                    ViewState["tags"] = dtTags;

                    rptTags.DataSource = dtTags;
                    rptTags.DataBind();
                }
            }
            btnToImages.Visible = true;
        }
        else
        {
            iArticleID= Convert.ToInt32(ViewState["iArticleID"]);
        }
    }

    protected void btnToImages_Click(object sender, EventArgs e)
    {
        pageType = (ViewState["pageType"]!=null)?(NewsType)ViewState["pageType"]:pageType;
        string sImageMng = string.Format("ArticleImages.aspx?ID={0}&type={1}", iArticleID, (int)pageType);
        Response.Redirect(sImageMng);   
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        int iCatID = 0;

        switch ((NewsType)ViewState["pageType"])
        {
            case NewsType.MedicalCenters:
                iCatID = Convert.ToInt32(ddlMedCenters.SelectedValue);
                break;
            case NewsType.hotels:
                iCatID = Convert.ToInt32(ddlMedCenters.SelectedValue);
                break;
            case NewsType.Wiki:
                if(ddlWikiSubCat.SelectedValue!="0")
                    iCatID = Convert.ToInt32(ddlWikiSubCat.SelectedValue);
                else
                    iCatID = Convert.ToInt32(ddlWiki.SelectedValue);
                break;
            case NewsType.aboutUS:
                iCatID = (int)NewsType.aboutUS;
                break;
            case NewsType.deadSea:
                iCatID = (int)NewsType.deadSea;
                break;
            default:
                // Add article
                iCatID = Convert.ToInt32(ddlCategories.SelectedValue);
                break;
        }

        string sBrowserTitle = txtBrowserTitle.Text;
        string sTitle = txtTitle.Text;
        string sSubTitle = Helper.CutString(txtSubTitle.Value);
        string sArticle = edArticle.Value;
        
        string sPageName = (txtUrl.Text.Trim().Length>0)?txtUrl.Text:sTitle;
        string sDateTime = txtPublishDate.Text.Trim() + " " + txtPublishTime.Text.Trim();
        string sqlDate =Helper.ConvertToSqlDateTime(DateTime.Now.ToString());
        if (sDateTime.Length > 1)
        {
            sqlDate = Helper.ConvertToSqlDateTime(sDateTime);
        }

        Dal.arParams.Clear();
        Dal.arParams.Add(iArticleID);
        Dal.arParams.Add(iCatID);
        Dal.arParams.Add(sBrowserTitle);
        Dal.arParams.Add(sTitle);
        Dal.arParams.Add(ab.ConvertToEnglishText(sPageName)); //PageName
        Dal.arParams.Add(sSubTitle);
        Dal.arParams.Add(sArticle);
        Dal.arParams.Add(sqlDate.ToString());
        Dal.arParams.Add(chkShowArticle.Checked);
        Dal.arParams.Add(chkShowDateDime.Checked);

        iArticleID = Convert.ToInt32(Dal.ExecuteDBspOneValue("Admin_UpdateArticle", Dal.arParams,true));
        
        // Add tags to article
        foreach (DataRow dr in dtTags.Rows)
        {
            Dal.arParams.Clear();
            Dal.arParams.Add(iArticleID);
            Dal.arParams.Add(Convert.ToInt32(dr["KeyID"]));
            Dal.ExecuteDBsp("Admin_InsertTagToArticle", Dal.arParams);
        }

        if (iArticleID > 0)
        {
            // Insert keywrds for specific article
            PageHeaderData.SetArticleKeywords(iArticleID, pageType, txtPageKeywords.Text);
            string sImageMng = string.Format("ArticleImages.aspx?ID={0}&type={1}", iArticleID, Convert.ToInt32(ViewState["pageType"]));
            Response.Redirect(sImageMng);
        }
    }

    protected void btnAddTag_Click(object sender, EventArgs e)
    {
        DataRow dr=dtTags.NewRow();
        dr["KeyID"]=cmbTags.SelectedItem.Value;
        dr["KeyName"]=cmbTags.SelectedItem.Text;
        dtTags.Rows.Add(dr);

        ViewState["tags"] = dtTags;

        rptTags.DataSource = dtTags;
        rptTags.DataBind();
       
    }

    // Add new tag
    protected void cmbTags_ItemInserting(object sender, ComboBoxItemInsertEventArgs e)
    {
        ImageButton btn = new ImageButton();
        Dal.arParams.Clear();
        Dal.arParams.Add(e.Item.Text);
        e.Item.Value = Dal.ExecuteDBspOneValue("usp_KeyWordInsert", Dal.arParams, true).ToString();
    }

    protected void imgDelete_Click(object sender, ImageClickEventArgs e)
    {
        int iTagID;
        Int32.TryParse(((ImageButton)sender).CommandArgument.ToString(), out iTagID);
        DataRow dr = dtTags.Select("keyid=" + iTagID)[0];
        dtTags.Rows.Remove(dr);
        ViewState["tags"] = dtTags;
        rptTags.DataSource = dtTags;
        rptTags.DataBind();
        if (iArticleID > 0)
        {
            Dal.arParams.Clear();
            Dal.arParams.Add(iArticleID);
            Dal.arParams.Add(iTagID);
            Dal.ExecuteDBsp("Admin_DeleteTagToArticle", Dal.arParams);
        }
    }

    protected void ddlMedCenters_SelectedIndexChanged(object sender, EventArgs e)
    {
        ViewState["medcenters"] = Convert.ToInt32(ddlMedCenters.SelectedValue);
    }

    protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
    {
        pageType = (NewsType)Convert.ToInt32(ddlCategories.SelectedValue);
        ViewState["pageType"] = pageType;
        SetPageType();
    }

    private void SetPageType()
    {
        ViewState["pnlAddArticleVisible"] = true;
        pnlAddArticle.Style.Clear();

        switch (pageType)
        {
            case NewsType.deadSea:
                pnlPublicationDate.Visible = false;
                updTags.Visible = false;
                pnlMedCenters.Visible = false;
                GetArticleToEditbyType((int)NewsType.deadSea);
                btnToImages.Visible = true;
                pnlWiki.Visible = false;
                break;

            case NewsType.news:
                pnlPublicationDate.Visible = true;
                pnlMedCenters.Visible = false;
                updTags.Visible = true;
                pnlWiki.Visible = false;
                break;

            case NewsType.MedicalTourism:
                pnlPublicationDate.Visible = true;
                pnlMedCenters.Visible = false;
                updTags.Visible = true;
                pnlWiki.Visible = false;
                break;

            case NewsType.MedicalCenters:
                updTags.Visible = false;
                chkShowDateDime.Checked= false;
                pnlPublicationDate.Visible = false;
                pnlWiki.Visible = false;
                pnlMedCenters.Visible = true;
                List<CategoryItem> Items = Category.ByAncestors((int)NewsType.MedicalCenters);
                try
                {
                    if (ddlMedCenters.Items[0].Text != Items[0].cTitle)
                    {
                        ddlMedCenters.DataSource = Items;
                        ddlMedCenters.DataBind();
                    }
                }
                catch { }
                if (ddlMedCenters.SelectedIndex == -1)
                {
                    ddlMedCenters.DataSource = Category.ByAncestors((int)NewsType.MedicalCenters);
                    ddlMedCenters.DataBind();
                }
                break;

            case NewsType.hotels:
                updTags.Visible = false;
                chkShowDateDime.Checked = false;
                pnlPublicationDate.Visible = false;
                pnlWiki.Visible = false;
                pnlMedCenters.Visible = true;
                Items = Category.ByAncestors((int)NewsType.hotels);
                try
                {
                    if (ddlMedCenters.Items[0].Text != Items[0].cTitle)
                    {
                        ddlMedCenters.DataSource = Items;
                        ddlMedCenters.DataBind();
                    }
                }
                catch { }
                if (ddlMedCenters.SelectedIndex == -1)
                {
                    ddlMedCenters.DataSource = Items;
                    ddlMedCenters.DataBind();
                }
                break;

            case NewsType.Wiki:
                pnlPublicationDate.Visible = false;
                pnlMedCenters.Visible = false;
                updTags.Visible = false;
                pnlWiki.Visible = true;
                if (ddlWiki.SelectedIndex == -1)
                {
                    ddlWiki.DataSource = Category.ByAncestors((int)NewsType.Wiki);
                    ddlWiki.DataBind();
                    ddlWiki_SelectedIndexChanged(this, new EventArgs());
                }
                break;

            case NewsType.aboutUS:
                GetArticleToEditbyType((int)NewsType.aboutUS);
                pnlPublicationDate.Visible = false;
                updTags.Visible = false;
                pnlWiki.Visible = false;
                chkShowArticle.Visible = false;
                txtSubTitle.Visible = false;
                break;
        }
    }

    protected void ddlWiki_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            ddlWikiSubCat.Items.Clear();
            ddlWikiSubCat.DataSource = Category.ByAncestors(Convert.ToInt32(ddlWiki.SelectedValue));
            ddlWikiSubCat.DataBind();
            ddlWikiSubCat.Items.Insert(0, new ListItem("Подкатегория не выбрана", "0"));
        }
        catch { }
    }
}
